// @ts-ignore
import Hierarchy from '@antv/hierarchy';
// @ts-ignore
import { Markup, Model } from '@antv/x6';

interface HierarchyResult {
  id: number
  x: number
  y: number
  data: defs.DataModelRelationVo
  children: HierarchyResult[]
}

export const getMindmapData = (data: defs.DataModelRelationVo) => {
  const result = Hierarchy.mindmap(data, {
    direction: 'H',
    getHeight() {
      return 80
    },
    getWidth() {
      return 190
    },
    getHGap() {
      return 80
    },
    getVGap() {
      return 44
    },
    getSide: () => {
      return 'right'
    },
  })
  return result;
}

//
export const getModelCells = (data: defs.DataModelRelationVo, onRemoveEvent: (data: any) => void, onEditEvent: (data: any) => void) => {
  const model: Model.FromJSONData = { nodes: [], edges: [] }
  const traverse = (data: HierarchyResult) => {
    if (data) {
      model.nodes?.push({
        id: `${data.id}`,
        x: data.x,
        y: data.y,
        shape: 'entity',
        width: 190,
        height: 80,
        data: {...data.data, onRemoveEvent, onEditEvent},
        attrs: {
          body: {
            fill: '#5F95FF',
            stroke: 'transparent',
          },
        },
      })
    }
    if (data.children) {
      data.children.forEach((item: HierarchyResult) => {
        model.edges?.push({
          shape: 'mindmap-edge',
          source: {
            cell: `${data.id}`,
            anchor:
            {
              name: 'right',
              args: {
                // dx: -16,
              },
            },
          },
          target: {
            cell: `${item.id}`,
            anchor:
            {
              name: 'left',
              // args: {
              //   dx: -16,
              // },
            },
          },
          data: {
            source: data.data,
            target: item.data
          },
          defaultLabel: {
            markup: Markup.getForeignObjectMarkup(),
            attrs: {
              fo: {
                width: 54,
                height: 20,
                x: -27,
                y: -10,
              },
            },
          },
          label: {
            position: 0.5,
          },

        })
        traverse(item)
      })
    }
  }
  const result = getMindmapData(data);
  traverse(result);
  return model;
}
